package com.chdwmp.product.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author: wendong.hu
 * @Date: 2018/4/21
 * @Time: 3:04
 * @Description: redis锁
 */
@Component
public class RedisLockUtils {
    private static Logger logger = LoggerFactory.getLogger(com.chdwmp.product.utils.RedisLockUtils.class);

    private static RedisTemplate redisTemplate;

    /**
     * 获取锁的等待时间默认1s
     */
    private static final int DEFAULT_WAIT_TIME = 1;

    /**
     * 拥有锁的有效时间默认2s
     */
    private static final int DEFAULT_HOLD_TIME = 2;
    private static final int HOUR_HOLD_TIME = 3600;

    private static Random random = new Random();

    @Autowired
    public RedisLockUtils(RedisTemplate redisTemplate) {
        com.chdwmp.product.utils.RedisLockUtils.redisTemplate = redisTemplate;
    }

    /**
     * 加锁
     * @param key
//     * @param value 当前时间+超时时间
     * @param waitTime 过期时间
     * @return
     */
    public boolean lock(String key, int waitTime) {
        if(redisTemplate.opsForValue().setIfAbsent(key, key)) {//相当于SETNX，setIfAbsent方法设置了为true,没有设置为false
            if (waitTime <=0){
                redisTemplate.expire(key, HOUR_HOLD_TIME, TimeUnit.SECONDS);//获取一个小时的锁
            }else {
                redisTemplate.expire(key, waitTime, TimeUnit.SECONDS);//获取指定秒数的锁
            }
            return true;
        }
        return false;//拿到锁的就有执行权力，拿不到的只有重新再来，重新再来只得是让用户手动继续抢单
    }

    /**
     * 解锁
     * @param key
     */
    public static void unlock(String key) {
        redisTemplate.delete(key);
    }


}